package c05;

import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.glu.GLU;

public class Game {
	public static final String GAME_TITLE = "My Game";
	private static final int FRAMERATE = 60;
	private static boolean finished;
	private static float angle;

	private Game() {
	}

	public static void main(String[] args) {
		try {
			init();
			run();
		} catch (Exception e) {
			e.printStackTrace(System.err);
		} finally {
			cleanup();
		}

		System.exit(0);
	}

	private static void init() throws Exception {
		Display.setTitle(GAME_TITLE);
		DisplayMode displayMode = new DisplayMode(800, 600);
		Display.setDisplayMode(displayMode);
		Display.create();
		GL11.glViewport(0, 0,Display.getDisplayMode().getWidth(),Display.getDisplayMode().getHeight());

		Display.setVSyncEnabled(true);
		//Display.create();

		GL11.glMatrixMode(GL11.GL_PROJECTION);
		GL11.glLoadIdentity();
		GL11.glFrustum(-100.0, 100.0, -100.0, 100.0, 10, 500.0);
		//GLU.gluPerspective( 65.0f, (float)Display.getDisplayMode().getWidth()/Display.getDisplayMode().getHeight(), -100.0f, 200.0f);

		//GL_MODELVIEW = viewing transformation + modeling transformation
		// viewing - gluLookAt(),
		GL11.glMatrixMode(GL11.GL_MODELVIEW);
		GL11.glLoadIdentity();
		GLU.gluLookAt(0f, 0f, 20.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);

		
		GL11.glClearColor (0f, 0f, 0f, 0f);
		
		GL11.glEnable(GL11.GL_CULL_FACE);
		GL11.glCullFace(GL11.GL_BACK);
		//GL11.glFrontFace(GL11.GL_CCW);
		GL11.glFrontFace(GL11.GL_CW);

		GL11.glEnable(GL11.GL_DEPTH_TEST);
		GL11.glDepthMask(true);
		GL11.glDepthFunc(GL11.GL_LESS);
		GL11.glDepthRange(0, 1);

	}

	/**
	 * Runs the game (the "main loop")
	 */
	private static void run() {
		while (!finished) {
			Display.update();

			if (Display.isCloseRequested()) {
				finished = true;
			} else if (Display.isActive()) {
				logic();
				
				//GL11.glLoadIdentity();
				//
				render();
				Display.sync(FRAMERATE);
			} else {
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
				}
				logic();
				if (Display.isVisible() || Display.isDirty()) {
					render();
				}
			}
		}
	}

	/**
	 * Do any game-specific cleanup
	 */
	private static void cleanup() {
		Display.destroy();
	}

	/**
	 * Do all calculations, handle input, etc.
	 */
	private static void logic() {
		if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {
			finished = true;
		}
		angle += 0.5f % 360;
	}

	private static void render() {
		GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_STENCIL_BUFFER_BIT);
		GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
		GL11.glPushMatrix();

		GL11.glTranslatef(0, 0, 0.0f);
		GL11.glRotatef(angle, 0, 0, 1.0f);

		Cube.wireCube(20);
		
		//Cube.solidCube(20);
		GL11.glFlush();
		
		GL11.glPopMatrix();

	}
}
